#!/usr/bin/env python
# coding: utf-8

# In[2]:


import tushare as ts
import pandas as pd
import talib

# 设置Tushare的token
ts.set_token('6f4ed3cc824c2d45087664dec52d197dfc411c36f4ed520ed8c35c50')
pro = ts.pro_api()

# 选择股票代码
stock_code = '600519.SH'

# 获取近5年的日线行情数据
start_date = '20200415'
end_date = '20250415'
df = pro.daily(ts_code=stock_code, start_date=start_date, end_date=end_date)

# 按日期升序排序
df = df.sort_values(by='trade_date')
df['trade_date'] = pd.to_datetime(df['trade_date'])
df.set_index('trade_date', inplace=True)

# 计算技术指标
# 简单移动平均线 (SMA)
df['SMA_5'] = talib.SMA(df['close'], timeperiod=5)
df['SMA_20'] = talib.SMA(df['close'], timeperiod=20)

# 相对强弱指数 (RSI)
df['RSI'] = talib.RSI(df['close'], timeperiod=14)

# 布林带 (Bollinger Bands)
df['upper_band'], df['middle_band'], df['lower_band'] = talib.BBANDS(df['close'], timeperiod=20)

# 输出结果
print(df[['open', 'high', 'low', 'close', 'SMA_5', 'SMA_20', 'RSI', 'upper_band', 'middle_band', 'lower_band']])
    


# In[3]:


import tushare as ts
import pandas as pd
import talib
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

# 设置Tushare的token
ts.set_token('6f4ed3cc824c2d45087664dec52d197dfc411c36f4ed520ed8c35c50')
pro = ts.pro_api()

# 选择股票代码
stock_code = '600519.SH'

# 获取近5年的日线行情数据
start_date = '20200415'
end_date = '20250415'
df = pro.daily(ts_code=stock_code, start_date=start_date, end_date=end_date)

# 按日期升序排序
df = df.sort_values(by='trade_date')
df['trade_date'] = pd.to_datetime(df['trade_date'])
df.set_index('trade_date', inplace=True)

# 计算技术指标
df['SMA_5'] = talib.SMA(df['close'], timeperiod=5)
df['SMA_20'] = talib.SMA(df['close'], timeperiod=20)
df['RSI'] = talib.RSI(df['close'], timeperiod=14)
df['upper_band'], df['middle_band'], df['lower_band'] = talib.BBANDS(df['close'], timeperiod=20)

# 生成目标变量：未来1天的收益率是否为正
df['next_day_return'] = df['close'].pct_change().shift(-1)
df['target'] = (df['next_day_return'] > 0).astype(int)

# 去除包含缺失值的行
df = df.dropna()

# 划分特征和目标变量
X = df[['open', 'high', 'low', 'close', 'SMA_5', 'SMA_20', 'RSI', 'upper_band', 'middle_band', 'lower_band']]
y = df['target']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建并训练随机森林模型
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# 进行预测
y_pred = model.predict(X_test)

# 计算收益率
test_df = X_test.copy()
test_df['target'] = y_test
test_df['prediction'] = y_pred
test_df['next_day_return'] = df.loc[test_df.index, 'next_day_return']
test_df['strategy_return'] = test_df['next_day_return'] * test_df['prediction']
total_return = (1 + test_df['strategy_return']).cumprod()[-1] - 1

# 模型评价
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)

print(f"总收益率: {total_return:.2%}")
print(f"准确率: {accuracy:.2%}")
print(f"精确率: {precision:.2%}")
print(f"召回率: {recall:.2%}")
print(f"F1分数: {f1:.2%}")
    


# In[ ]:




